<?php

// Start session management and include necessary functions
session_start();
require_once('../dao/database.php');
require_once('../dao/user_db.php');
require_once('../domain/User.php');

// Get the action to perform
if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else if (isset($_GET['action'])) {
    $action = $_GET['action'];
} else {
    $action = 'show_home';
}

//// If the user isn't logged in, force the user to login
//if (!isset($_SESSION[Constants::SESSION_ROLE])) {
//    $action = 'login';
//}

// Perform the specified action
switch ($action) {
    case 'login':
        if (isset($_POST['nickname']) && $_POST['password']) {
            $nickname = trim($_POST['nickname']);
            $password = trim($_POST['password']);
            $password = hash( 'sha256', $password );
            $users = get_user($nickname, $password);
            if (count($users) == 1) {
                if ($users[0]->isConfirmed()){
                    $_SESSION[Constants::SESSION_ROLE] = Constants::ROLE_IS_USER;
                    $_SESSION[Constants::SESSION_USER] = $users[0];
                    $_SESSION[Constants::SESSION_USER_NAME] = $users[0]->getVorname().' '.$users[0]->getNachname();
                    header("Location: .");
                } else {
                    $login_message = 'Sie müssen Ihre Anmeldung, die Sie per E-Mail erhalten haben, noch bestätigen!';
                    include('loginView.php');                    
                }
            } else {
                if(count($users) == 0){
//                    $error_message = 'Benutzername oder Passwort ist nicht korrekt.';
                    $login_message = 'Benutzername oder Passwort ist nicht korrekt.';
                    include('loginView.php');
                } else {
                    $error_message = 'Interner Fehler: Errorcode 0002';
                    include('../errors/error.php');
                }
                exit();
            }
        } else {
            $login_message = '';
            include('loginView.php');
        }
        break;
    case 'show_home':
        include('homeView.php');
        break;
    case 'logout':
        $_SESSION = array();   // Clear all session data from memory
        session_destroy();     // Clean up the session ID
        $login_message = 'You have been logged out.';
        include('homeView.php');
        break;
    case 'confirmed':
        $login_message = "Ihre Anmeldung wurde bestätigt. Bitte melden Sie sich jetzt an.";
        include('loginView.php');
        break;
}
?>